#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

enum udpserver
{
    SOCKET_ERROR = 1,
    BIND_ERROR

};

const static int defaultsockfd  = -1;
const uint16_t defaultport = 8888;
class UdpServer
{
public:
    UdpServer(const std::string& ip ,uint16_t port = defaultport):_sockfd(defaultsockfd),_ip(ip),_port(port)
    {
    }

    void InitServer()
    {
        // 1. 创建udp socket --必须要做的
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(FATAL, "socket error, %s, %d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);
        //2.0 填充sockaddr_in 结构
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port); 
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // 2. bind sockfd ip和网络信息(IP(?) + port);
        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error, %s, %d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind socket success\n");

    }

    void Start()
    {
    }

    ~UdpServer()
    {
    }

private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
};